package main

import (
	"bytes"
	"encoding/base64"
	"flag"
	"fmt"
	"image"
	"image/jpeg"
	"log"
	"net"
	"os"

	"google.golang.org/grpc"

	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"

	pb "git.oschina.net/sukibean/yolomonitor/protobuf"
)

var (
	tls        = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
	certFile   = flag.String("cert_file", "testdata/server1.pem", "The TLS cert file")
	keyFile    = flag.String("key_file", "testdata/server1.key", "The TLS key file")
	jsonDBFile = flag.String("json_db_file", "testdata/route_guide_db.json", "A json file containing a list of features")
	port       = flag.Int("port", 50050, "The server port")
)

type imageDetectServer struct {
	objects []*pb.DetectData
}

// func (s *imageDetectServer) GetMultiobject(req *pb.DetectRequest, stream pb.ImageDetect_GetMultiojbectServer) error {
func (s *imageDetectServer) GetMultiObject(req *pb.DetectRequest, stream pb.ImageDetect_GetMultiObjectServer) error {
	for _, obj := range s.objects {

		if err := stream.Send(obj); err != nil {
			return err
		}

	}
	return nil
}

// func serialize(point *pb.Point) string {
// 	return fmt.Sprintf("%d %d", point.Latitude, point.Longitude)
// }

func newServer() *imageDetectServer {
	s := new(imageDetectServer)

	reader, err := os.Open("test.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer reader.Close()
	// reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))
	m, _, err := image.Decode(reader)

	buf := new(bytes.Buffer)
	jpeg.Encode(buf, m, nil)

	strimg := base64.StdEncoding.EncodeToString(buf.Bytes())
	s.objects = []*pb.DetectData{
		{
			X:      3,
			Y:      4,
			Width:  40,
			Height: 50,
			Type:   strimg,
		},
		{
			X:      4,
			Y:      4,
			Width:  30,
			Height: 40,
			Type:   strimg,
		},
	}

	// s.loadFeatures(*jsonDBFile)
	// s.routeNotes = make(map[string][]*pb.RouteNote)
	return s
}

func main() {
	flag.Parse()
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		grpclog.Fatalf("failed to listen: %v", err)
	}
	var opts []grpc.ServerOption
	if *tls {
		creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
		if err != nil {
			grpclog.Fatalf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)
	pb.RegisterImageDetectServer(grpcServer, newServer())
	grpcServer.Serve(lis)
}
